<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="100px">
      <el-form-item label="租户组名称" prop="tenantGroupName">
        <el-input v-model="queryParams.tenantGroupName" placeholder="请输入租户组名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系人" prop="tenantGroupLinkName">
        <el-input v-model="queryParams.tenantGroupLinkName" placeholder="请输入联系人名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="tenantGroupLinkMobile">
        <el-input v-model="queryParams.tenantGroupLinkMobile" placeholder="请输入联系电话" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="是否临期" prop="expireTemp">
        <el-select v-model="queryParams.expireTemp" placeholder="请选择" style="width: 200px">
          <el-option :label="item.label" :value="item.value" v-for="(item,index) in lqValue" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['gc:zhz:xz']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :scrollbar-always-on="true" :data="groupList">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="租户组编号" prop="tenantGroupId" width="300" />
      <el-table-column label="租户组名称" prop="tenantGroupName" :show-overflow-tooltip="true" width="200">
        <template #default="scope">
          <div style="display: flex;align-items: center;">
            {{scope.row.tenantGroupName}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="联系人" prop="tenantGroupLinkName" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="联系电话" prop="tenantGroupLinkMobile" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="联系地址" prop="tenantGroupLinkAddress" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="有效期" prop="tenantGroupLinkMobile" :show-overflow-tooltip="true" width="200">
        <template #default="scope">
          {{scope.row.tenantGroupExpireStatus=='F'?'永久':`${scope.row.tenantGroupExpireDate}到期`}}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.tenantGroupAvl" @change="handleStatusChange(scope.row)" active-value="Y"
            inactive-value="N"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="200" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-tooltip content="一键复制租户" placement="top" v-if="scope.row.tenantGroupId !== 1">
            <el-button link type="primary" icon="Connection" @click="handleCopy(scope.row)"
              v-hasPermi="['gc:zhz:fz']"></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top" v-if="scope.row.tenantGroupId !== 1">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['gc:zhz:xg']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.tenantGroupId !== 1">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['gc:zhz:sc']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改租户组配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="租户组名称" prop="tenantGroupName">
          <el-input v-model="form.tenantGroupName" placeholder="请输入租户组名称" />
        </el-form-item>
        <el-form-item label="租户组联系人" prop="tenantGroupLinkName">
          <el-input v-model="form.tenantGroupLinkName" placeholder="请输入租户组联系人" />
        </el-form-item>
        <el-form-item label="租户组联系电话" prop="tenantGroupLinkMobile">
          <el-input v-model="form.tenantGroupLinkMobile" type="phone" placeholder="请输入租户组联系电话" />
        </el-form-item>
        <el-form-item label="租户组联系地址" prop="tenantGroupLinkAddress">
          <el-input v-model="form.tenantGroupLinkAddress" placeholder="请输入租户组联系地址" />
        </el-form-item>
        <el-form-item label="状态" prop="tenantGroupAvl">
          <el-radio-group v-model="form.tenantGroupAvl">
            <el-radio v-for="dict in statusList" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有效期类型" prop="tenantGroupExpireStatus">
          <el-radio-group v-model="form.tenantGroupExpireStatus">
            <el-radio value="F">永久</el-radio>
            <el-radio value="T">限时</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="截止日期" prop="tenantGroupExpireDate" v-if="form.tenantGroupExpireStatus=='T'">
          <el-date-picker format="YYYY-MM-DD" :disabled-date="disabledDate" value-format="YYYY-MM-DD"
            v-model="form.tenantGroupExpireDate" type="date" placeholder="选择截止日期" />
        </el-form-item>
        <el-form-item label="备注" prop="tenantGroupDesc">
          <el-input v-model="form.tenantGroupDesc" type="textarea" placeholder="请输入租户组备注" />
        </el-form-item>
        <el-form-item label="租户列表" v-if="!form.tenantGroupId">
          <view>
            <el-button @click="addTent">添加租户</el-button>
          </view>
        </el-form-item>
        <div v-if="!form.tenantGroupId">
          <el-table :data="form.tenantCreateParams" style="width: 100%">
            <el-table-column prop="序号" label="序号" width="50">
              <template #default="scope">
                {{scope.$index+1}}
              </template>
            </el-table-column>
            <el-table-column prop="tenantName" label="租户名称">
              <template #default="scope">
                <el-input v-model="scope.row.tenantName"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="tenantCode" label="租户编码">
              <template #default="scope">
                <el-input v-model="scope.row.tenantCode"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="applicantId" label="应用类型">
              <template #default="scope">
                <el-select v-model="scope.row.applicantId" placeholder="选择应用">
                  <el-option v-for="item in appLicationList" :key="item.applicantName" :label="item.applicantName"
                    :value="item.applicantId" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button link type="primary" @click="deleteTent(scope.$index)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="tenantGroup">
  import {
    addgroup,
    delgroup,
    getgroup,
    listgroup,
    updategroup,
    changeAvl,
    getAllgroupTent
  } from "@/api/system/tenantgroup";
  import {
    listapplicant,
  } from "@/api/system/applicant";
  const router = useRouter();
  const route = useRoute()
  const { proxy } = getCurrentInstance();
  const lqValue = ref([{
    value: 'Y',
    label: '是'
  }, {
    value: 'N',
    label: '否'
  }])
  const groupList = ref([]);
  const open = ref(false);
  const appLicationList = ref([])
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const dateRange = ref([]);
  const menuOptions = ref([]);
  const menuExpand = ref(false);
  const menuNodeAll = ref(false);
  const deptExpand = ref(true);
  const deptNodeAll = ref(false);
  const deptOptions = ref([]);
  const openDataScope = ref(false);
  const menuRef = ref(null);
  const deptRef = ref(null);
  const statusList = ref([{
    label: '启用',
    value: 'Y'
  }, {
    label: '禁用',
    value: 'N'
  }])
  /** 数据范围选项*/
  const dataScopeOptions = ref([
    { value: "1", label: "全部数据权限" },
    { value: "2", label: "自定数据权限" },
    { value: "3", label: "本部门数据权限" },
    { value: "4", label: "本部门及以下数据权限" },
    { value: "5", label: "仅本人数据权限" }
  ]);
  /** 查询应用列表 */
  function getAppLication() {
    listapplicant({ pageNum: 1, pageSize: 10000 }).then(response => {
      appLicationList.value = response.rows
    });
  }
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      expireTemp: 0,
      tenantGroupName: undefined,
      tenantGroupLinkName: undefined,
      tenantGroupLinkMobile: '',
      tenantGroupExpireStatus: '',
      tenantGroupAvl: ''
    },
    rules: {
      tenantGroupName: [{ required: true, message: "租户组名称不能为空", trigger: "blur" }],
      tenantGroupLinkName: [{ required: true, message: "租户组联系人不能为空", trigger: "blur" }],
      tenantGroupLinkAddress: [{ required: true, message: "租户组联系地址不能为空", trigger: "blur" }],
      tenantGroupExpireDate: [{ required: true, message: "截止日期不能为空", trigger: "blur" }],
      tenantGroupLinkMobile: [{ required: true, message: "租户组联系电话不能为空", trigger: "blur" }, {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur',
      }],
      tenantGroupExpireStatus: [{ required: true, message: "有效期类型不能为空", trigger: "blur" }],
      tenantGroupAvl: [{ required: true, message: "状态不能为空", trigger: "blur" }],
    },
  });
  //添加租户
  const addTent = () => {
    let item = {
      applicantId: '',
      tenantCode: '',
      tenantName: ''
    }
    form.value.tenantCreateParams = [...form.value.tenantCreateParams, { ...item }];
  }
  const deleteTent = (index) => {
    form.value.tenantCreateParams.splice(index, 1)
  }
  const disabledDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7; // 8.64e7 毫秒数代表一天
  };
  const { queryParams, form, rules } = toRefs(data);
  /** 租户状态修改 */
  function handleStatusChange(row) {
    let text = row.tenantGroupAvl === "Y" ? "启用" : "禁用";
    proxy.$modal.confirm('确认要"' + text + '""' + row.tenantGroupName + '"用户组吗?').then(function() {
      return changeAvl({ tenantGroupId: row.tenantGroupId, tenantGroupAvl: row.tenantGroupAvl });
    }).then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    }).catch(function() {
      row.tenantGroupAvl = row.tenantGroupAvl === "Y" ? "N" : "Y";
    });
  }
  /** 查询租户组列表 */
  function getList() {
    loading.value = true;
    let formQueryParam = { ...queryParams.value };
    formQueryParam.expireTemp = formQueryParam.expireTemp == 0 ? '' : formQueryParam.expireTemp
    listgroup(proxy.addDateRange(formQueryParam, dateRange.value)).then(response => {
      groupList.value = response.rows
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  // 一键复制

  async function copyTextToClipboard(text) {
    if (!navigator.clipboard) {
      // navigator.clipboard API不可用时使用旧的document.execCommand方法
      var textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        var successful = document.execCommand('copy');
        if (successful) {
          proxy.$modal.msgSuccess('复制成功');
        } else {
          proxy.$modal.msgWarning('复制失败');
        }
      } catch (err) {
        console.error('Fallback: Error copying text!', err);
      }
      document.body.removeChild(textArea);
      return;
    }
    try {
      await navigator.clipboard.writeText(text);
      proxy.$modal.msgSuccess('复制成功');
    } catch (err) {
      proxy.$modal.msgWarning('复制失败');
    }
  }
  const handleCopy = async (row) => {
    //一键复制
    getAllgroupTent({ tenantGroupId: row.tenantGroupId }).then((res) => {
      let textToCopy =
        `${row.tenantGroupName}(${row.tenantGroupLinkName} ${row.tenantGroupLinkMobile})有效期为${row.tenantGroupExpireStatus=='F'?'永久':`${row.tenantGroupExpireDate}到期`}，共有${row.tenantCount}个租户：`;
      res.data.forEach((label, index) => {
        let text = `\n${index+1}.${label.tenantName} ${label.applicantName} ${label.tenantUrl} ${label.adminUserName} 初始密码:${label.adminPassword}`
        textToCopy += text
      })
      copyTextToClipboard(textToCopy)
    })
  }
  /** 重置按钮操作 */
  function resetQuery() {
    dateRange.value = [];
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      expireTemp: '',
      tenantGroupName: undefined,
      tenantGroupLinkName: undefined,
      tenantGroupLinkMobile: '',
      tenantGroupExpireStatus: '',
      tenantGroupAvl: ''
    }
    handleQuery();
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const tenantGroupIds = row.tenantGroupId || ids.value;
    proxy.$modal.confirm('是否确认删除租户组编号为"' + tenantGroupIds + '"的数据项?').then(function() {
      return delgroup(tenantGroupIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("system/role/export", {
      ...queryParams.value,
    }, `role_${new Date().getTime()}.xlsx`);
  }

  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.tenantGroupId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 租户组状态修改 */
  function handlegroupAvlChange(row) {
    let text = row.groupAvl === "0" ? "启用" : "停用";
    proxy.$modal.confirm('确认要"' + text + '""' + row.groupName + '"租户组吗?').then(function() {
      return changeRolegroupAvl(row.tenantGroupId, row.groupAvl);
    }).then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    }).catch(function() {
      row.groupAvl = row.groupAvl === "0" ? "1" : "0";
    });
  }

  /** 更多操作 */
  function handleCommand(command, row) {
    switch (command) {
      case "handleDataScope":
        handleDataScope(row);
        break;
      case "handleAuthUser":
        handleAuthUser(row);
        break;
      default:
        break;
    }
  }

  /** 分配用户 */
  function handleAuthUser(row) {
    router.push("/system/role-auth/user/" + row.tenantGroupId);
  }


  /** 所有部门节点数据 */
  function getDeptAllCheckedKeys() {
    // 目前被选中的部门节点
    let checkedKeys = deptRef.value.getCheckedKeys();
    // 半选中的部门节点
    let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }

  /** 重置新增的表单以及其他数据  */
  function reset() {
    if (menuRef.value != undefined) {
      menuRef.value.setCheckedKeys([]);
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    deptExpand.value = true;
    deptNodeAll.value = false;
    form.value = {
      tenantGroupName: undefined,
      tenantGroupLinkName: undefined,
      tenantGroupLinkMobile: '',
      tenantGroupExpireStatus: 'F',
      tenantGroupAvl: 'Y',
      tenantCreateParams: []
    };
    proxy.resetForm("roleRef");
  }

  /** 添加租户组 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加租户组";
  }

  /** 修改租户组 */
  function handleUpdate(row) {
    reset();
    const tenantGroupId = row.tenantGroupId || ids.value;
    getgroup(tenantGroupId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改租户组";
    });
  }

  /** 根据租户组ID查询菜单树结构 */
  function getgroupMenuTreeselect(tenantGroupId) {
    return roleMenuTreeselect(tenantGroupId).then(response => {
      menuOptions.value = response.menus;
      return response;
    });
  }

  /** 根据租户组ID查询部门树结构 */
  function getDeptTree(tenantGroupId) {
    return deptTreeSelect(tenantGroupId).then(response => {
      deptOptions.value = response.depts;
      return response;
    });
  }

  /** 树权限（展开/折叠）*/
  function handleCheckedTreeExpand(value, type) {
    if (type == "menu") {
      let treeList = menuOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    } else if (type == "dept") {
      let treeList = deptOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    }
  }

  /** 树权限（全选/全不选） */
  function handleCheckedTreeNodeAll(value, type) {
    if (type == "menu") {
      menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
    } else if (type == "dept") {
      deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
    }
  }

  /** 树权限（父子联动） */
  function handleCheckedTreeConnect(value, type) {
    if (type == "menu") {
      form.value.menuCheckStrictly = value ? true : false;
    } else if (type == "dept") {
      form.value.deptCheckStrictly = value ? true : false;
    }
  }

  /** 所有菜单节点数据 */
  function getMenuAllCheckedKeys() {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }

  /** 提交按钮 */
  function submitForm() {
    let pass = true
    if (!form.value.tenantGroupId && form.value.tenantCreateParams && form.value.tenantCreateParams.length) {
      form.value.tenantCreateParams.forEach((a, index) => {
        if (!a.applicantId || !a.tenantCode || !a.tenantName) {
          pass = false
        }
      })
    }
    if (!pass) {
      proxy.$modal.msgWarning("租户列表下内容不能有空~");
      return
    }
    // if (form.value.tenantGroupExpireStatus == 'T' && !form.value.tenantGroupExpireDate) {
    //   proxy.$modal.msgWarning("请选择截止日期~");
    //   return
    // }
    proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
        if (form.value.tenantGroupId != undefined) {
          updategroup(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addgroup(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }

  /** 选择租户组权限范围触发 */
  function dataScopeSelectChange(value) {
    if (value !== "2") {
      deptRef.value.setCheckedKeys([]);
    }
  }

  /** 分配数据权限操作 */
  function handleDataScope(row) {
    reset();
    const deptTreeSelect = getDeptTree(row.tenantGroupId);
    getgroup(row.tenantGroupId).then(response => {
      form.value = response.data;
      openDataScope.value = true;
      nextTick(() => {
        deptTreeSelect.then(res => {
          nextTick(() => {
            if (deptRef.value) {
              deptRef.value.setCheckedKeys(res.checkedKeys);
            }
          });
        });
      });
      title.value = "分配数据权限";
    });
  }

  /** 提交按钮（数据权限） */
  function submitDataScope() {
    if (form.value.tenantGroupId != undefined) {
      form.value.deptIds = getDeptAllCheckedKeys();
      dataScope(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        openDataScope.value = false;
        getList();
      });
    }
  }

  /** 取消按钮（数据权限）*/
  function cancelDataScope() {
    openDataScope.value = false;
    reset();
  }
  queryParams.value.expireTemp = route.query.expireTemp ? route.query.expireTemp : '';
  getList();
  getAppLication()
</script>